package org.jeecg.modules.deepseek.pojo;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.openai.api.ResponseFormat;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.List;

@Slf4j
@Configurable
public class ChatRequestExample {


    private final WebClient webClient;
    private final ObjectMapper objectMapper;



    public ChatRequestExample() {
        this.webClient = WebClient.builder()
                .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.USER_AGENT, "YourAppName/1.0")
                .build();
        this.objectMapper = new ObjectMapper();
    }
    @Value("${spring.ai.openai.base-url}")
    private static String OPENAI_API_URL="https://api.siliconflow.cn/v1/chat/completions";

    @Value("${openai.api.api-key}")
    private static String OPENAI_API_KEY="sk-dpenhzjhsqibrsuhqpoyoplcwsusjxdduqwtdveudiygyjwa";

    public static  ResponseEntity<OpenAiApi.ChatCompletion> requestDeepSeekChat(List<OpenAiApi.FunctionTool> tools, List< ChatRequest.Message> messages) {
        // 1. 构造 ChatRequest 对象

        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setModel("deepseek-ai/DeepSeek-V3");
        // 1.1 设置消息
        chatRequest.setMessages(messages);
        // 1.2 设置工具及其参数
        chatRequest.setTools(tools);
        // 1.3 设置工具选择
        chatRequest.setToolChoice("auto");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + OPENAI_API_KEY);
        headers.set("Content-Type", "application/json");
//       String a= """
//               {"type": "function", "function": {"name": "my_function"}}""";
        try {
            String s = new ObjectMapper().writeValueAsString(chatRequest);
            log.debug("模型请求结构: \n{}", s);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        HttpEntity<ChatRequest> requestEntity = new HttpEntity<>(chatRequest, headers);

        // 3. 使用 RestTemplate 发送请求
        String url =OPENAI_API_URL; // 替换为实际的接口地址
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<OpenAiApi.ChatCompletion> responseEntity = restTemplate.exchange(
                url, HttpMethod.POST, requestEntity, OpenAiApi.ChatCompletion.class);
        try {
            String s = new ObjectMapper().writeValueAsString(responseEntity);
            log.debug("模型输出结果: \n{}", s);
//            System.out.println("s = " + s);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return responseEntity;
    }


    public  Flux<String> ChatDeepSeekSteam (ChatRequest chatRequest) throws JsonProcessingException {

        chatRequest.setStream(true);
        chatRequest.setModel("deepseek-chat");
        String s = objectMapper.writeValueAsString(chatRequest);
////        JsonNode jsonNode1 = objectMapper.readTree(chatRequest);
//        System.out.println("jsonNode1 = " + s);
        return webClient.post()
                .uri(OPENAI_API_URL)
                .headers(headers -> headers.set(HttpHeaders.AUTHORIZATION, "Bearer "+OPENAI_API_KEY)) // 设置 Token
                .bodyValue(chatRequest)
                .retrieve()
                .bodyToFlux(String.class) // 逐行读取目标 API 响应流
                .map(chunk -> {
                    try {
                        // 解析 JSON 数据
                        JsonNode jsonNode = objectMapper.readTree(chunk);
                        JsonNode contentNode = jsonNode.at("/choices/0/delta/content");
                        return contentNode.isTextual() ? contentNode.asText() : "";
                    } catch (Exception e) {
                        System.err.println("Failed to parse chunk: " + chunk);
                        return ""; // 返回空字符串，避免中断流
                    }
                })
                .filter(content -> !content.isEmpty()) // 过滤空内容
                .doOnNext(content -> {
                    System.out.println("Parsed content: " + content); // 日志记录解析后的数据
                });
    }
    public static  ResponseEntity<OpenAiApi.ChatCompletion> requestDeepSeekJSON(List< ChatRequest.Message> messages) {
        // 1. 构造 ChatRequest 对象

        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setModel("deepseek-ai/DeepSeek-V3");
        // 1.1 设置消息
        chatRequest.setMessages(messages);
        // 1.2 设置工具及其参数
        String jsonSchema = """
                {
                  "type": "object",
                  "properties": {
                    "data_note": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "source_note_id": {
                            "type": "integer",
                            "description": "当前笔记的唯一标识 ID"
                          },
                          "target_note_id": {
                            "type": "integer",
                            "description": "与当前笔记关联的目标笔记 ID"
                          },
                          "relation_type": {
                            "type": "string",
                            "description": "笔记之间的关联类型，如：关键词关联、语义关联、上下文关联、主题关联、情绪关联、日期关联等"
                          },
                          "relation_keyword": {
                            "type": "string",
                            "description": "用于建立关联的关键内容，如关键词、语义点、上下文、情绪、时间等"
                          }
                        },
                        "required": [
                          "source_note_id",
                          "target_note_id",
                          "relation_type",
                          "relation_keyword"
                        ]
                      },
                      "description": "笔记之间的关联数据数组"
                    }
                  },
                  "required": [
                    "data_note"
                  ]
                }
        """;
        chatRequest.setResponse_format(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, jsonSchema));
        // 1.3 设置工具选择
        chatRequest.setToolChoice("auto");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + OPENAI_API_KEY);
        headers.set("Content-Type", "application/json");
//       String a= """
//               {"type": "function", "function": {"name": "my_function"}}""";
        try {
            String s = new ObjectMapper().writeValueAsString(chatRequest);
            log.debug("模型请求结构: \n{}", s);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        HttpEntity<ChatRequest> requestEntity = new HttpEntity<>(chatRequest, headers);

        // 3. 使用 RestTemplate 发送请求
        String url =OPENAI_API_URL; // 替换为实际的接口地址
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<OpenAiApi.ChatCompletion> responseEntity = restTemplate.exchange(
                url, HttpMethod.POST, requestEntity, OpenAiApi.ChatCompletion.class);
        try {
            String s = new ObjectMapper().writeValueAsString(responseEntity);
            log.debug("模型输出结果: \n{}", s);
//            System.out.println("s = " + s);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return responseEntity;
    }


}


